package myTest;

import org.joda.time.DateTime;

import java.util.stream.IntStream;


public class UidGenerator {

    /**
     * 序列在id中占的位数
     */
    private final long sequenceBits = 12L;
    /**
     * 时间戳向左移12位
     */
    private final long workIdLeftShift = sequenceBits;
    /**
     * 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)
     */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long workIdHash;
    /**
     * 毫秒内序列(0~4095)
     */
    private long sequence = 0L;
    /**
     * 上次生成ID的时间戳
     */
    private long lastTimestamp = -1L;


    public UidGenerator() {
        String instanceId = "osg-teslagateway-7ff557cc9f-zpq25:tesla-gateway:8080";
        int hash = instanceId.hashCode();
        System.out.println(hash);
        System.out.println(Integer.toBinaryString(hash));
        workIdHash = hash;
    }

    public synchronized String nextId() {
        return nextId(null);
    }

    public synchronized String nextId(String prefix) {
        long timestamp = timeGen();

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format(
                "Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            // 毫秒内序列溢出
            if (sequence == 0) {
                // 阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        // 时间戳改变，毫秒内序列重置
        else {
            sequence = 0L;
        }

        // 上次生成ID的时间戳
        lastTimestamp = timestamp;
        if (prefix == null) {
            prefix = "";
        }
        return prefix + new DateTime(timestamp).toString("yyMMddHHmmssSSS")
            + Long.toString((workIdHash << workIdLeftShift) | sequence);
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     *
     * @param lastTimestamp 上次生成ID的时间戳
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     *
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        UidGenerator uidGenerator = new UidGenerator();
        System.out.println(uidGenerator.nextId());
        IntStream.range(0,5000).forEach(i->{
            System.out.println(uidGenerator.nextId());
        });
    }

}
